package com.errol.msgcenterclient.autoconfig;

import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.renjia.msgcenter.properties.MsgCenterMqProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * 消息中心批量消息通道
 *
 * @author zhang xiao bin
 * @version v1.0
 * @date 2021/05/12
 * @since v5.2.0
 **/
@Slf4j
@Configuration
@ComponentScan(basePackages = "com.renjia.msgcenter")
public class AliYunMqProducerAutoConfiguration {

    @Resource
    private MsgCenterMqProperties config;

    /**
     * MQ顺序消费生产者，消息即时消费，用于业务通知的场景
     */
    @Bean(initMethod = "start", destroyMethod = "shutdown", name = "commonProducer")
    @ConditionalOnProperty(prefix = AliYunMqProducerSelector.PROPERTY_PREFIX, name = AliYunMqProducerSelector.ENABLE_COMMON_PRODUCER, havingValue = AliYunMqProducerSelector.ENABLE_STRING)
    public ProducerBean commonProducer() {
        ProducerBean producer = this.generateProducer(config.getCommon().getGroupId());
        log.info("钉钉机器人批量消息通道生产端已启动");
        return producer;
    }

    /**
     * 钉钉机器人因为有频率限制，采用批量消息队列
     */
    @Bean(initMethod = "start", destroyMethod = "shutdown", name = "dingRobotProducer")
    @ConditionalOnProperty(prefix = AliYunMqProducerSelector.PROPERTY_PREFIX, name = AliYunMqProducerSelector.ENABLE_DING_ROBOT_PRODUCER, havingValue = AliYunMqProducerSelector.ENABLE_STRING)
    public ProducerBean dingRobotProducer() {
        ProducerBean producer = this.generateProducer(config.getDingRobot().getGroupId());
        log.info("钉钉机器人批量消息通道生产端已启动");
        return producer;
    }

    private ProducerBean generateProducer(String groupId) {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.GROUP_ID, groupId);
        properties.setProperty(PropertyKeyConst.AccessKey, config.getAccessKey());
        properties.setProperty(PropertyKeyConst.SecretKey, config.getSecretKey());
        properties.setProperty(PropertyKeyConst.NAMESRV_ADDR, config.getNameSrvAddr());
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, config.getTimeoutMillis());
        ProducerBean producer = new ProducerBean();
        producer.setProperties(properties);
        return producer;
    }

}
